#include "BeepTask.h"
#include "cmsis_os.h"
#include "tim.h"
#include "GlobalVars.h"

#define BEEP_PIN GPIO_PIN_0
#define BEEP_PORT GPIOA

#define MAX_VOLUME 1000
#define MIN_VOLUME 100

uint16_t currentVolume = MAX_VOLUME;

void setBeepFrequency(uint32_t frequency) {
    uint32_t prescaler = 72000000 / (frequency * MAX_VOLUME) - 1;
    uint32_t period = MAX_VOLUME - 1;

    TIM2->PSC = prescaler;
    TIM2->ARR = period;
    TIM2->CCR1 = currentVolume * 3 / 4;  // 75% of current volume
}

void setVolume(uint16_t volume) {
    currentVolume = (volume > MAX_VOLUME) ? MAX_VOLUME :
                    (volume < MIN_VOLUME) ? MIN_VOLUME : volume;
}

void BeepTask(void *pvParameters) {
    HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);

    while (1) {
#if JinYin
        beepState = 3; // 仅调试用
#endif
        switch (beepState) {
            case 0:
                setVolume(MAX_VOLUME * 3 / 4);
                setBeepFrequency(3000);
                break;
            case 1:
                setVolume(MAX_VOLUME * 7 / 8);
                setBeepFrequency(3500);
                break;
            case 2:
                setVolume(MAX_VOLUME);
                setBeepFrequency(4000);
                break;
            case 3:
            default:
//                HAL_TIM_PWM_Stop(&htim2, TIM_CHANNEL_1);  // 停止PWM输出
                __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, __HAL_TIM_GET_AUTORELOAD(&htim2));

//                GPIO_InitTypeDef GPIO_InitStruct = {0};
//                GPIO_InitStruct.Pin = BEEP_PIN;
//                GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
//                GPIO_InitStruct.Pull = GPIO_NOPULL;
//                GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
//                HAL_GPIO_Init(BEEP_PORT, &GPIO_InitStruct);
//
//                HAL_GPIO_WritePin(BEEP_PORT, BEEP_PIN, GPIO_PIN_SET);
                break;
        }
        vTaskDelay(pdMS_TO_TICKS(100));
    }
}
